<template>
  <el-dialog v-model="visible" :title="`${mode === 'add' ? '新增' : '编辑'}课程`" width="50%" top="5vh">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="课程名称" prop="courseName">
        <el-input v-model="form.courseName" placeholder="请输入课程名称" />
      </el-form-item>

      <el-form-item label="课程类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择课程类型" @change="handleTypeChange">
          <el-option label="一对一" value="1" />
          <el-option label="小组课" value="2" />
          <el-option label="公开课" value="3" />
          <el-option label="试听课" value="4" />
        </el-select>
      </el-form-item>

      <el-form-item label="乐器分类" prop="icId">
        <el-select v-model="form.icId" placeholder="请选择乐器分类">
          <el-option v-for="instrument in props.instrumentsOptions" :key="instrument.id" :label="instrument.icName"
            :value="instrument.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="教室" prop="classroomId">
        <el-select v-model="form.classroomId" placeholder="全部教室" clearable>
          <el-option v-for="classroom in classroomList" 
          :key="classroom.id" :label="classroom.classroomName" :value="classroom.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="教师" prop="teacherId">
        <el-select v-model="form.teacherId" placeholder="选择教师" clearable filterable remote
          :remote-method="queryTeacher">
          <el-option v-for="teacher in teachers" :key="teacher.id" :label="teacher.teacherName" :value="teacher.id" />
        </el-select>
      </el-form-item>

      <el-form-item v-if="form.type != '3'" label="学员" :prop=" form.type != '3' ? 'studentIds' : ''">
        <el-select v-model="form.studentIds" :placeholder="`请选择${form.type == '1' ? '' : '多位'}学员`"
          :multiple="form.type != '1'" filterable remote
          :remote-method="queryStudent">
          <el-option v-for="student in students" :key="student.id" :label="student.studentName" :value="student.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="课程时长(分钟)" prop="duration">
        <el-input-number v-model="form.duration" :min="30" :max="180" />
      </el-form-item>

      <el-form-item label="排课方式" prop="scheduleType">
        <el-radio-group v-model="form.scheduleType">
          <el-radio value="1">单次课</el-radio>
          <el-radio v-if="form.type != '4' && form.type != '3'" value="2">重复排课</el-radio>
        </el-radio-group>
      </el-form-item>

      <template v-if="form.scheduleType == '1'">
        <el-form-item label="上课时间" prop="scheduleTime">
          <el-date-picker v-model="form.scheduleTime" type="datetime" placeholder="选择上课时间"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
      </template>

      <template v-else>
        <el-form-item label="重复周期" prop="repeatType">
          <el-select v-model="form.repeatType" placeholder="请选择重复周期">
            <el-option label="每天" value="1" />
            <el-option label="每周" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="每周重复" prop="repeatWeekly" v-if="form.repeatType == '2'">
          <el-checkbox-group v-model="form.repeatWeekly">
            <el-checkbox label="1">星期一</el-checkbox>
            <el-checkbox label="2">星期二</el-checkbox>
            <el-checkbox label="3">星期三</el-checkbox>
            <el-checkbox label="4">星期四</el-checkbox>
            <el-checkbox label="5">星期五</el-checkbox>
            <el-checkbox label="6">星期六</el-checkbox>
            <el-checkbox label="7">星期日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="开始日期" prop="startTime">
              <el-date-picker v-model="form.startTime" type="date" placeholder="选择开始日期" value-format="YYYY-MM-DDTHH:mm:ss" />
        </el-form-item>
        <el-form-item label="上课时间" prop="scheduleTime">
          <el-time-picker v-model="form.scheduleTime" placeholder="选择时间" value-format="HH:mm:ss" />
        </el-form-item>
      </template>
      <el-form-item label="总课时" prop="totalLessons">
        <el-input-number v-model="form.totalLessons" :min="1" :max="1000" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getInIds } from '@/api/student'
import { formatDateTime } from '@/utils/dateUtils'

const props = defineProps({
  modelValue: Boolean,
  courseData: Object,
  mode: String, // 'add' or 'edit'
  teachers: Array,
  queryTeacher: Function,
  instrumentsOptions: Array,
  classroomList: Array
})

const emit = defineEmits(['update:modelValue', 'success', 'updateTeachers'])

const visible = ref(false)
const formRef = ref(null)
const students = ref([])

import { getStudentList } from '@/api/student'

const queryStudent = async (query) => {
  const result = await getStudentList({ page: 1, pageSize: 10, studentName: query })
  students.value = result.data.list
}

// 表单数据
const form = reactive({
  courseName: '',
  type: '1',
  icId: '',
  totalLessons: 1,
  finishedLessons: 0,
  classroomId: '',
  teacherId: '',
  studentIds: [],
  duration: 45,
  scheduleType: '1',
  scheduleTime: '',
  repeatType: '1',
  repeatWeekly: [],
  startTime: formatDateTime(new Date(), 'YYYY-MM-DDTHH:mm:ss')
})

// 表单验证规则
const rules = {
  courseName: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择课程类型', trigger: 'change' }],
  icId: [{ required: true, message: '请选择乐器分类', trigger: 'change' }],
  totalLessons: [{ required: true, message: '请输入总课时', trigger: 'blur' }],
  classroomId: [{ required: true, message: '请选择教室', trigger: 'change' }],
  teacherId: [{ required: true, message: '请选择教师', trigger: 'change' }],
  studentIds: [{ required: true, message: '请选择学员', trigger: 'change' }],
  duration: [{ required: true, message: '请输入课程时长', trigger: 'blur' }],
  scheduleType: [{ required: true, message: '请选择排课方式', trigger: 'change' }],
  scheduleTime: [{ required: true, message: '请选择上课时间', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  repeatWeekly: [
    {
      required: true,
      message: '请至少选择一天',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.scheduleType == '2' && form.repeatType == '2' && (!value || value.length === 0)) {
          callback(new Error('请至少选择一天'))
        } else {
          callback()
        }
      }
    }
  ],
  repeatType: [
    {
      required: true,
      message: '请选择重复周期',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.scheduleType == '2' && !value) {
          callback(new Error('请选择重复周期'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 监听显示状态
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val && props.mode === 'edit' && props.courseData) {
    // 处理学员数据，确保是数组
    getInIds({ ids: props.courseData.studentIds.join(',') }).then(res => {
      students.value = res.data
      // 处理教师数据
      emit('updateTeachers', [{
        id: props.courseData.teacherId,
        teacherName: props.courseData.teacherName
      }])
      Object.assign(form, props.courseData)
      // form.startTime = formatDateTime(new Date(), 'YYYY-MM-DDTHH:mm:ss')
      form.studentIds = form.type == '1' ? form.studentIds[0] : form.studentIds
    })
  } else if (val && props.mode === 'add') {
    resetForm()
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

watch(form, (val) => {
  if (val.scheduleType == '1')
    form.totalLessons = 1
  if (val.type == '4' || val.type == '3')
    form.scheduleType = '1'
})

// 课程类型变化处理
const handleTypeChange = (type) => {
  // 一对一课程时，如果选了多个学员，只保留第一个
  if (type == '1' && form.studentIds.length > 1) {
    form.studentIds = [form.studentIds[0]]
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    courseName: '',
    type: '1',
    icId: '',
    finishedLessons: 0,
    totalLessons: 10,
    classroomId: '',
    teacherId: '',
    studentIds: [],
    duration: 45,
    scheduleType: '1',
    scheduleTime: '',
    repeatType: '1',
    repeatWeekly: [],
    startTime: formatDateTime(new Date(), 'YYYY-MM-DDTHH:mm:ss')
  })
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    // 处理数据
    const submitData = { ...form }
    // studentIds 任何时候都是数组
    if (submitData.studentIds && !Array.isArray(submitData.studentIds)) {
      submitData.studentIds = [submitData.studentIds]
    }
    // 将repeatWeekly数组转换为字符串
    if (submitData.repeatWeekly && Array.isArray(submitData.repeatWeekly)) {
      submitData.repeatWeekly = submitData.repeatWeekly.join(',')
    }

    emit('success', submitData)
    visible.value = false
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

</script>
